package com.hwadee.springboot_lx.service;

import com.hwadee.springboot_lx.entity.Log;
import com.hwadee.springboot_lx.entity.LogSearchCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class RedisService {

    private final JedisPool jedisPool;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public RedisService(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    // 搜索日志并根据给定的条件过滤
    public List<Log> searchLogs(LogSearchCriteria criteria) {
        String key = "logs";
        List<Object> rawLogs = redisTemplate.opsForList().range(key, 0, -1); // 获取原始列表
        List<Log> logs = new ArrayList<>();

        // 将 Object 转换为 Log 类型
        for (Object obj : rawLogs) {
            if (obj instanceof Log) {
                logs.add((Log) obj);
            }
        }

        // 根据筛选条件过滤日志
        return logs.stream().filter(log -> logMatchesCriteria(log, criteria)).collect(Collectors.toList());
    }

    // 导出指定 logId 的日志
    public byte[] exportLog(Long logId) {
        // 从 Redis 获取指定 logId 的日志内容
        Log log = (Log) redisTemplate.opsForValue().get("log:" + logId);
        return log != null ? log.getDetails().getBytes(StandardCharsets.UTF_8) : new byte[0];
    }

    // 导出所有日志，并将其压缩成一个 ZIP 文件
    public byte[] exportAllLogs() {
        // 从 Redis 中获取所有日志
        List<Object> logsObject = redisTemplate.opsForList().range("logs", 0, -1);
        List<Log> logs = logsObject.stream()
                .filter(log -> log instanceof Log)  // 确保类型正确
                .map(log -> (Log) log)  // 强制转换为 Log 类型
                .collect(Collectors.toList());

        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
             ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream)) {

            for (Log log : logs) {
                ZipEntry zipEntry = new ZipEntry(log.getId() + ".txt");
                zipOutputStream.putNextEntry(zipEntry);
                zipOutputStream.write(log.getDetails().getBytes(StandardCharsets.UTF_8));
                zipOutputStream.closeEntry();
            }
            zipOutputStream.finish();
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("Failed to export logs", e);
        }
    }

    // 根据条件过滤日志
    private boolean logMatchesCriteria(Log log, LogSearchCriteria criteria) {
        // 实际过滤逻辑可以根据 logType, startDate, searchQuery 来过滤
        // 示例：这里暂时使用 log.getLogType().equals(criteria.getLogType()) 来过滤
        return log.getLogType().equals(criteria.getLogType());
    }

    // 恢复 Redis 数据
    public void restoreRedis(String filePath) {
        File backupFile = new File(filePath);
        if (!backupFile.exists()) {
            System.out.println("Backup file not found.");
            return;
        }

        System.out.println("Restoring Redis data from " + filePath);
        try (Jedis jedis = jedisPool.getResource()) {
            // 清空当前所有数据
            jedis.flushAll();

            // 获取 Redis 数据目录路径
            String redisDataDir = System.getenv("REDIS_DATA_DIR");
            if (redisDataDir == null) redisDataDir = "/var/lib/redis";
            File redisDumpFile = new File(redisDataDir + "/dump.rdb");

            // 复制备份文件
            copyBackupFile(backupFile, redisDumpFile);

            // 重启 Redis 服务
            restartRedisService();
            System.out.println("Redis restore completed successfully.");
        } catch (IOException | InterruptedException e) {
            System.out.println("Restore failed: " + e.getMessage());
        }
    }

    // 复制备份文件到 Redis 数据目录
    private void copyBackupFile(File backupFile, File redisDumpFile) throws IOException {
        Files.copy(backupFile.toPath(), redisDumpFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        System.out.println("Backup file copied to Redis data directory.");
    }

    // 重启 Redis 服务
    private void restartRedisService() throws IOException, InterruptedException {
        ProcessBuilder builder = new ProcessBuilder("sudo", "systemctl", "restart", "redis");
        Process process = builder.start();
        process.waitFor();
        System.out.println("Redis service restarted.");
    }

    // 备份 Redis 数据
    public void backupRedis(String filePath) {
        try (Jedis jedis = jedisPool.getResource()) {
            // 使用 RDB 方式备份 Redis 数据
            jedis.save();

            String redisDataDir = System.getenv("REDIS_DATA_DIR");
            if (redisDataDir == null) redisDataDir = "/var/lib/redis";
            File redisRdbFile = new File(redisDataDir + "/dump.rdb");

            if (!redisRdbFile.exists()) {
                System.out.println("Redis RDB file not found.");
                return;
            }

            // 备份文件复制到目标路径
            File backupFile = new File(filePath);
            if (backupFile.exists()) {
                backupFile.delete();
            }
            Files.copy(redisRdbFile.toPath(), backupFile.toPath());
            System.out.println("Redis backup successful.");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Redis backup failed.");
        }
    }
}
